import { patrolingSetMode } from '@/api'
import { mode } from '@/shared'
import { useCarStore } from '@/stores/car'
import { useElMessage } from '@/stores/elMessage'
import { i18n } from '@/utils'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export enum Mode {
  STOP = 'STOP',
  AUTO = 'AUTO',
  MANUAL = 'MANUAL'
}

const messageMap = {
  [Mode.AUTO]: i18n.global.t('zi-zhu-qie-huan-cheng-gong'),
  [Mode.MANUAL]: i18n.global.t('shou-dong-qie-huan-cheng-gong'),
  [Mode.STOP]: i18n.global.t('ting-zhi-qie-huan-cheng-gong')
}

export const useModeStore = defineStore('mode', () => {
  const carMode = ref<Mode | null>(null)
  const carStore = useCarStore()
  const isDown = {
    [Mode.STOP]: false,
    [Mode.AUTO]: false,
    [Mode.MANUAL]: false
  }

  async function setMode(type: Mode) {
    isDown[type] = true
    carMode.value = type
    await patrolingSetMode(carStore.currentCar, mode[type])
    const elMessage = useElMessage()
    elMessage.setElMessage(messageMap[type], 'success')
  }

  function toggleAutoMode(status: boolean) {
    isDown[Mode.AUTO] = status
    if (status) {
      if (isDown[Mode.STOP]) {
        setMode(Mode.STOP)
      } else {
        setMode(Mode.AUTO)
      }
    } else {
      isDown[Mode.AUTO] = false
      if (isDown[Mode.STOP]) {
        setMode(Mode.STOP)
      } else {
        setMode(Mode.MANUAL)
      }
    }
  }

  function toggleStopMode(status: boolean) {
    isDown[Mode.STOP] = status
    if (status) {
      setMode(Mode.STOP)
    } else {
      isDown[Mode.STOP] = false
      if (isDown[Mode.AUTO]) {
        setMode(Mode.AUTO)
      } else {
        setMode(Mode.MANUAL)
      }
    }
  }

  return {
    setMode,
    carMode,
    toggleAutoMode,
    toggleStopMode
  }
})
